<template>
  <div class="register-page">
    <!-- 动态背景 -->
    <div class="background">
      <canvas class="particle-canvas"></canvas>
      <div class="floating-shapes">
        <div style="width: 150px; height: 150px; top: 10%; left: 5%"></div>
        <div style="width: 100px; height: 100px; top: 60%; left: 80%"></div>
        <div style="width: 120px; height: 120px; top: 30%; left: 70%"></div>
      </div>
    </div>

    <div class="container">
      <div class="register-card">
        <h2 class="title">用户注册</h2>
        <div v-if="registerMsg" :class="{ 'error-message': registerError, 'success-message': !registerError }">{{ registerMsg }}</div>

        <div class="form-container">
          <div class="form-group">
            <label for="phone">手机号</label>
            <input 
              id="phone" 
              v-model="phone" 
              type="text" 
              maxlength="11" 
              placeholder="请输入手机号" 
              @blur="checkPhoneExists" 
              @input="clearPhoneError" 
              required 
            />
            <span v-if="phoneError" class="field-error">{{ phoneError }}</span>
          </div>

          <div class="form-group">
            <label for="idCard">身份证号</label>
            <input 
              id="idCard" 
              v-model="idCard" 
              type="text" 
              maxlength="18" 
              placeholder="请输入身份证号" 
              @blur="checkIdCardExists" 
              required 
            />
            <span v-if="idCardError" class="field-error">{{ idCardError }}</span>
          </div>

          <div class="form-group">
            <label for="name">姓名</label>
            <input 
              id="name" 
              v-model="name" 
              type="text" 
              placeholder="请输入姓名" 
              required 
            />
          </div>

          <div class="form-group">
            <label for="password">密码</label>
            <input 
              id="password" 
              v-model="password" 
              type="password" 
              placeholder="请输入密码" 
              required 
            />
          </div>

          <div class="form-group">
            <label for="code">验证码</label>
            <div class="code-group">
              <input 
                id="code" 
                v-model="code" 
                type="text" 
                maxlength="6" 
                placeholder="请输入验证码" 
                required 
              />
              <button 
                type="button" 
                class="send-code-btn" 
                @click="sendCode" 
                :disabled="codeSending || !phone || phoneError"
              >
                {{ codeBtnText }}
              </button>
            </div>
          </div>

          <div class="form-group">
            <label>人脸验证</label>
            <div class="face-recognition">
              <view v-if="currentAction" class="action-prompt">
                <view class="action-icon" :class="currentAction">
                  <text v-if="currentAction === 'shake_head'">摇头</text>
                  <text v-else-if="currentAction === 'open_mouth'">张嘴</text>
                  <text v-else-if="currentAction === 'blink_eye'">眨眼</text>
                </view>
                <text>{{ actionDescription }}</text>
                <text class="recording-status" v-if="isRecording">
                  正在录制... {{ recordingTime }}s
                </text>
              </view>
              
              <!-- H5端视频容器 -->
              <!-- #ifdef H5 -->
              <div id="video-container" class="video-container" v-if="isCameraActive"></div>
              <!-- #endif -->
              
              <!-- 微信小程序端摄像头 -->
              <!-- #ifdef APP-PLUS || MP-WEIXIN -->
              <camera
                v-if="isCameraActive"
                device-position="front"
                flash="off"
                style="width: 100%; height: 300rpx;"
                @error="onCameraError"
              ></camera>
              <!-- #endif -->
              
              <view class="face-buttons">
                <button type="button" @click="toggleCamera">{{ isCameraActive ? '关闭摄像头' : '开启摄像头' }}</button>
                <button type="button" @click="startRecording" :disabled="!isCameraActive || isRecording">开始录制</button>
                <button type="button" @click="getNewAction" :disabled="!isCameraActive">更换动作</button>
              </view>
              <view v-if="recordedFrames.length > 0" class="recording-preview">
                <text>已录制 {{ recordedFrames.length }} 帧</text>
              </view>
            </div>
          </div>

          <button class="register-btn" type="button" @click="onRegister" :disabled="registering">
            {{ registering ? '注册中...' : '注册' }}
          </button>
        </div>

        <div class="links">
          <text @click="goToLogin">已有账户？立即登录</text>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { NETWORK_CONFIG } from '@/config/network.js'
import { ref, onMounted, onUnmounted, watch } from 'vue';


// 表单数据
const phone = ref('');
const idCard = ref('');
const name = ref('');
const password = ref('');
const code = ref('');

// 错误信息
const phoneError = ref('');
const idCardError = ref('');
const registerMsg = ref('');
const registerError = ref(false);

// 验证码相关
const codeSending = ref(false);
const codeBtnText = ref('发送验证码');
const registering = ref(false);

// 人脸识别相关
const isCameraActive = ref(false);
const currentAction = ref('');
const actionDescription = ref('');
const isRecording = ref(false);
const recordingTime = ref(0);
const recordedFrames = ref([]);
const recordingInterval = ref(null);
const frameCaptureInterval = ref(null);

// H5摄像头相关
const videoElement = ref(null);
const stream = ref(null);

let timer = null;

const checkPhoneExists = async () => {
  phoneError.value = '';
  if (!phone.value) {
    return;
  }
  
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    phoneError.value = '手机号格式不正确';
    return;
  }
  
  try {
    const res = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/auth/register/is-exists`,
      method: 'POST',
      data: {
        phone: phone.value,
        idCard: '',
        name: '',
        password: ''
      }
    })
    if (res.statusCode !== 200) {
      phoneError.value = res.data?.message || '手机号已存在';
    } else {
      phoneError.value = '';
    }
  } catch (e) {
    phoneError.value = '';
  }
};

const checkIdCardExists = async () => {
  idCardError.value = '';
  if (!/^\d{17}(\d|X|x)$/.test(idCard.value)) {
    idCardError.value = '身份证号格式不正确';
    return;
  }
  try {
    const res = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/auth/register/is-exists`,
      method: 'POST',
      data: {
        phone: '',
        idCard: idCard.value,
        name: '',
        password: ''
      }
    })
    if (res.statusCode !== 200) {
      idCardError.value = res.data?.message || '身份证号已存在';
    } else {
      idCardError.value = '';
    }
  } catch (e) {
    idCardError.value = '';
  }
};

const sendCode = async () => {
  if (!phone.value || phoneError.value) {
    uni.showToast({
      title: '请先输入正确的手机号',
      icon: 'none'
    });
    return;
  }

  try {
    codeSending.value = true;
    codeBtnText.value = '发送中...';
    
    const res = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/auth/register/send-code`,
      method: 'POST',
      data: {
        identifier: phone.value
      }
    });
    
    if (res.statusCode === 200) {
      uni.showToast({
        title: '验证码已发送，五分钟内有效',
        icon: 'success'
      });
      
      // 倒计时
      let countdown = 60;
      codeBtnText.value = `已发送(${countdown}s)`;
      
      if (timer) clearInterval(timer);
      
      timer = setInterval(() => {
        countdown--;
        codeBtnText.value = `已发送(${countdown}s)`;
        
        if (countdown <= 0) {
          clearInterval(timer);
          codeBtnText.value = '发送验证码';
          codeSending.value = false;
        }
      }, 1000);
    } else {
      codeBtnText.value = '发送验证码';
      codeSending.value = false;
      
      uni.showToast({
        title: res.data?.message || '发送验证码失败',
        icon: 'none'
      });
    }
  } catch (e) {
    codeBtnText.value = '发送验证码';
    codeSending.value = false;
    
    uni.showToast({
      title: e.message || '发送验证码失败',
      icon: 'none'
    });
  }
};

// 摄像头相关
const toggleCamera = async () => {
  if (isCameraActive.value) {
    stopCamera();
  } else {
    await startCamera();
  }
};

// 启动摄像头
const startCamera = async () => {
  try {
    // #ifdef H5
    const video = document.createElement('video');
    video.autoplay = true;
    video.playsInline = true;
    video.style.width = '100%';
    video.style.height = '300px';
    video.style.borderRadius = '12px';
    
    const container = document.querySelector('.face-recognition');
    if (container) {
      container.appendChild(video);
      videoElement.value = video;
    }
    
    const mediaStream = await navigator.mediaDevices.getUserMedia({ 
      video: { 
        facingMode: 'user',
        width: { ideal: 640 },
        height: { ideal: 480 }
      } 
    });
    video.srcObject = mediaStream;
    stream.value = mediaStream;
    isCameraActive.value = true;
    // #endif
    
    // #ifdef APP-PLUS || MP-WEIXIN
    isCameraActive.value = true;
    // #endif
  } catch (error) {
    console.error('摄像头访问失败:', error);
    uni.showToast({
      title: '摄像头权限被拒绝或设备不支持',
      icon: 'none'
    });
    isCameraActive.value = false;
  }
};

const onCameraError = (e) => {
  uni.showToast({ title: '摄像头错误', icon: 'none' });
  isCameraActive.value = false;
};

const startRecording = () => {
  if (!isCameraActive.value) return;
  isRecording.value = true;
  recordingTime.value = 0;
  recordedFrames.value = [];
  
  // 录制时间计时
  recordingInterval.value = setInterval(() => {
    recordingTime.value++;
    if (recordingTime.value >= 3) {
      stopRecording();
    }
  }, 1000);
  
  // 真实帧采集
  frameCaptureInterval.value = setInterval(() => {
    captureFrame();
  }, 200);
};

// 采集帧数据
const captureFrame = () => {
  console.log('开始采集帧数据...');
  // #ifdef H5
  if (videoElement.value) {
    const video = videoElement.value;
    console.log('视频元素存在，视频尺寸:', video.videoWidth, 'x', video.videoHeight);
    if (video.videoWidth && video.videoHeight) {
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      if (context) {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        const base64 = canvas.toDataURL('image/jpeg', 0.8);
        console.log('采集到真实base64数据，长度:', base64.length);
        recordedFrames.value.push(base64);
      } else {
        console.error('无法创建canvas上下文');
      }
    } else {
      console.warn('视频尺寸无效');
    }
  } else {
    console.warn('视频元素不存在');
  }
  // #endif
  
  // #ifdef APP-PLUS || MP-WEIXIN
  const cameraContext = uni.createCameraContext();
  if (cameraContext) {
    cameraContext.takePhoto({
      quality: 'high',
      success: (res) => {
        // 将图片路径转换为base64
        uni.getFileSystemManager().readFile({
          filePath: res.tempImagePath,
          encoding: 'base64',
          success: (fileRes) => {
            const base64 = 'data:image/jpeg;base64,' + fileRes.data;
            recordedFrames.value.push(base64);
          },
          fail: (err) => {
            console.error('读取图片失败:', err);
          }
        });
      },
      fail: (err) => {
        console.error('拍照失败:', err);
      }
    });
  }
  // #endif
};

const stopRecording = () => {
  isRecording.value = false;
  clearInterval(recordingInterval.value);
  clearInterval(frameCaptureInterval.value);
  if (recordedFrames.value.length < 5) {
    uni.showToast({
      title: '录制时间太短，请重试',
      icon: 'none'
    });
    recordedFrames.value = [];
    return;
  }
};

const stopCamera = () => {
  // #ifdef H5
  if (stream.value) {
    stream.value.getTracks().forEach(track => track.stop());
    stream.value = null;
  }
  if (videoElement.value) {
    videoElement.value.remove();
    videoElement.value = null;
  }
  // #endif
  isCameraActive.value = false;
};

// 获取新的动作要求
const getNewAction = async () => {
  try {
    const res = await uni.request({
      url: "${NETWORK_CONFIG.API_BASE_URL}/auth/login/face/action",
      method: "GET"
    });
    if (res.statusCode === 200) {
      const data = res.data;
      currentAction.value = data.action;
      actionDescription.value = data.description;
    } else {
      registerMsg.value = (res.data && res.data.message) || "获取动作要求失败";
    }
  } catch (error) {
    registerMsg.value = "获取动作要求失败: " + error.message;
  }
};

const onRegister = async () => {
  if (!phone.value || !idCard.value || !name.value || !password.value || !code.value) {
    uni.showToast({
      title: '请填写所有必填字段',
      icon: 'none'
    });
    return;
  }

  if (phoneError.value || idCardError.value) {
    uni.showToast({
      title: '请修正错误后再提交',
      icon: 'none'
    });
    return;
  }

  // 检查人脸识别数据
  if (recordedFrames.value.length === 0 || !currentAction.value) {
    uni.showToast({
      title: '请完成人脸识别验证',
      icon: 'none'
    });
    return;
  }

  registering.value = true;
  registerMsg.value = '';
  registerError.value = false;

  // 调试信息
  console.log('注册调试信息:');
  console.log('录制的帧数:', recordedFrames.value.length);
  console.log('第一帧数据预览:', recordedFrames.value[0] ? recordedFrames.value[0].substring(0, 50) + '...' : '无数据');
  console.log('当前动作:', currentAction.value);

  try {
    const res = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/auth/register`,
      method: 'POST',
      data: {
        phone: phone.value,
        idCard: idCard.value,
        name: name.value,
        password: password.value,
        code: code.value,
        frames: recordedFrames.value,
        action: currentAction.value
      }
    })
    if (res.statusCode === 200) {
      registerMsg.value = typeof res.data === 'string' ? res.data : (res.data.message || '注册成功');
      registerError.value = false;
      
      uni.showToast({
        title: '注册成功',
        icon: 'success'
      });
      
      // 注册成功后跳转到登录页
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/auth/login/index'
        });
      }, 2000);
    } else {
      throw new Error(res.data?.message || '注册失败');
    }
    
  } catch (e) {
    registerMsg.value = e.message || '注册失败';
    registerError.value = true;
    
    uni.showToast({
      title: e.message || '注册失败',
      icon: 'none'
    });
  } finally {
    registering.value = false;
  }
};

const clearPhoneError = () => {
  phoneError.value = '';
};

const goToLogin = () => {
  uni.navigateTo({
    url: '/pages/auth/login/index'
  });
};

onUnmounted(() => {
  stopCamera();
  if (timer) clearInterval(timer);
  if (recordingInterval.value) clearInterval(recordingInterval.value);
  if (frameCaptureInterval.value) clearInterval(frameCaptureInterval.value);
});

onMounted(() => {
  // #ifdef H5
  // 移动端键盘弹出处理
  const handleResize = () => {
    const vh = window.innerHeight * 0.01;
    document.documentElement.style.setProperty('--vh', `${vh}px`);
  };
  
  window.addEventListener('resize', handleResize);
  handleResize();
  
  // 防止iOS Safari中的橡皮筋效果
  document.body.addEventListener('touchmove', (e) => {
    if (e.target.closest('.register-card')) {
      e.preventDefault();
    }
  }, { passive: false });
  // #endif
  
  // 页面加载时获取动作要求
  getNewAction();
});
</script>

<style scoped>
body, html {
  margin: 0;
  padding: 0;
  width: 100vw;
  overflow-x: hidden;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background: #f6f8fa;
}

.register-page {
  min-height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #667eea;
  padding: 0;
  box-sizing: border-box;
  overflow-x: hidden;
  position: relative;
  z-index: 2;
}

.container {
  width: 100vw;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
  box-sizing: border-box;
}

.register-card {
  width: 100%;
  max-width: 450px;
  margin: 0 auto;
  background: #fff;
  border-radius: 20px;
  padding: 30px 24px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  border: 1px solid #eee;
}

.title {
  font-size: 1.8rem;
  font-weight: 700;
  color: #1a1a1a;
  margin-bottom: 5px;
  text-align: center;
  letter-spacing: -0.5px;
}

.form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 0.95rem;
  color: #4a5568;
  font-weight: 500;
  margin-bottom: 2px;
}

input, select {
  padding: 16px 14px;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  font-size: 1rem;
  outline: none;
  background: #f8fafc;
  font-family: inherit;
}

.field-error {
  color: #dc2626;
  font-size: 0.85rem;
  margin-top: 4px;
  font-weight: 500;
}

.code-group {
  display: flex;
  gap: 10px;
  align-items: stretch;
}

.code-group input {
  flex: 1;
}

.send-code-btn {
  padding: 16px 20px;
  background: #4f8cff;
  color: #fff;
  border: none;
  border-radius: 12px;
  font-size: 0.9rem;
  font-weight: 600;
  min-width: 100px;
}

.send-code-btn:disabled {
  background: #cbd5e1;
  color: #fff;
}

.register-btn {
  width: 100%;
  padding: 18px 0;
  background: #4f8cff;
  color: #fff;
  border: none;
  border-radius: 12px;
  font-size: 1.1rem;
  font-weight: 700;
  margin-top: 10px;
}

.register-btn:disabled {
  background: #cbd5e1;
  color: #fff;
}

.links {
  text-align: center;
  margin-top: 15px;
  font-size: 0.9rem;
  line-height: 1.5;
}

.links text {
  color: #4f8cff;
  text-decoration: none;
  margin: 0 8px;
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 6px;
}

.error-message {
  background: #fef2f2;
  color: #dc2626;
  border-radius: 12px;
  padding: 14px 16px;
  font-size: 0.9rem;
  text-align: center;
  border: 1px solid #fecaca;
  font-weight: 500;
}

.success-message {
  background: #f0fdf4;
  color: #16a34a;
  border-radius: 12px;
  padding: 14px 16px;
  font-size: 0.9rem;
  text-align: center;
  border: 1px solid #bbf7d0;
  font-weight: 500;
}

.face-recognition {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: center;
}
.video-container {
  width: 100%;
  height: 300rpx;
  border-radius: 12rpx;
  overflow: hidden;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.action-prompt {
  text-align: center;
  margin-bottom: 12px;
  padding: 12px;
  background: #e8f0fe;
  border-radius: 12px;
}
.action-icon {
  font-size: 32rpx;
  margin-bottom: 8px;
  color: #4f8cff;
}
.recording-status {
  color: #dc2626;
  font-weight: bold;
  margin-top: 8px;
}
.recording-preview {
  margin-top: 12px;
  padding: 8px;
  background: #e8f0fe;
  border-radius: 12px;
  text-align: center;
}

.face-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  margin-top: 12px;
  flex-wrap: wrap;
}

.face-buttons button {
  padding: 12px 16px;
  background: #4f8cff;
  color: #fff;
  border: none;
  border-radius: 10px;
  font-size: 0.9rem;
  font-weight: 600;
  min-width: 80px;
}

.face-buttons button:disabled {
  background: #cbd5e1;
  color: #fff;
}

.video-container {
  width: 100%;
  max-width: 100%;
  height: 250px;
  background: #000;
  border-radius: 16px;
  overflow: hidden;
  margin-bottom: 16px;
}

.face-preview {
  margin-top: 12px;
}

.background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 0;
  pointer-events: none;
}

.floating-shapes {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  pointer-events: none;
  z-index: 1;
}

.floating-shapes > div {
  position: absolute;
  border-radius: 50%;
  background: #fff2;
}

.particle-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 0;
  pointer-events: none;
}
</style>